//
//  JXNewTopicCtl.m
//  JiaoX
//
//  Created by yinqy on 15/3/2.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  发表新帖子

#import "JXNewTopicCtl.h"
#import "JXTextView.h"
#import "PicListView.h"
#import "JTSActionSheet.h"
#import "ShareOrderPopView.h"
#import "CustomShowView.h"
#import "ZYQAssetPickerController.h"
#import "JXNavigationController.h"
#import "UpYun.h"
#import "BBSModel.h"
#import "ModelArrayView.h"
#import "CartProdSub.h"
#import "ForumDataTool.h"
#import "SelfDataTool.h"


/**
 * 帖子标题最大字数 ，单位字节
 */
#define MAX_INPUT_WORD_FOR_TITLE 100
/**
 * 帖子标题和内容最小字数 ，单位字节
 */
#define MIN_INPUT_WORD_FOR_TITLE 8
/**
 * 帖子内容最大字数，单位字节
 */
#define MAX_INPUT_WORD_FOR_COTENT 2000

#import <MobileCoreServices/MobileCoreServices.h>

@interface JXNewTopicCtl ()<UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PicListViewDelegate,ZYQAssetPickerControllerDelegate,ModelArrayViewDelegate,ShareOrderPopViewDelegate>
{
    UIImagePickerController *_imagePickerController;
    
}
@property (nonatomic,weak)UIScrollView *scrollView;
@property (nonatomic,weak)UITextField *titleField;
@property (nonatomic,weak)UIView *splite1;
@property (nonatomic,weak)JXTextView *contentView;
@property (nonatomic,weak)PicListView *picListView;
@property (nonatomic,weak)UIView *splite2;
@property (nonatomic,weak)UIButton *chooseBtn;
@property (nonatomic,weak)UIView *splite3;
@property (nonatomic,weak)UIButton *publishBtn;//发表
@property (nonatomic,strong)UpYun *uy;//发表
@property (nonatomic,strong)NSMutableArray *imageUrlArray;
@property (nonatomic,strong)NSArray *modelArray;
@property (nonatomic,strong)MBProgressHUD *HUD;
@property (nonatomic,assign)NSInteger currentModelIndex;


//晒单
@property (nonatomic,copy)NSString *sharedId;
@property (nonatomic,copy)NSString *prodId;
@property (nonatomic,copy)NSString *prodName;
@end

@implementation JXNewTopicCtl

-(instancetype)initWithModelList:(NSArray *)array
{
   return [self initWithModelList:array currentModeIndex:-1];
}
-(instancetype)initWithModelList:(NSArray *)array currentModeIndex:(NSInteger)index{
    self = [super init];
    if (self) {
        self.modelArray = array;
        self.currentModelIndex = index;
    }
    return self;
}
-(instancetype)initWithSharedId:(NSString *)sharedId prodId:(NSString *)prodId ProdName:(NSString *)prodName{
    self = [super init];
    if (self) {
        self.sharedId = sharedId;
        self.prodId = prodId;
        self.prodName = prodName;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:JXGlobalColorBg];[self setTitle:@"发帖"];
    [self initView];
    
    if (_currentModelIndex!=-1) {
        [self modelBtnClickWithIndex:_currentModelIndex];
    }
    
    //如果不是晒单页面，并且版块列表为Null
    if ((self.modelArray==nil || self.modelArray.count==0) && ISBLANK(self.sharedId)) {
        //去请求modellist
        MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
        [ForumDataTool getModeList:^(BBSHomeData *result) {
            [HUD hide:YES];
            if (!result.code) {
                self.modelArray = result.modelList;
            }else{
                [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
            }
        } failure:^(NSError *error) {
            [HUD hide:YES];
            [DialogUtils showTipsWithView:self.navigationController.view String:@"获取版块列表失败"];
        }];
    }
    
    if (!ISBLANK(self.sharedId)) {
        [self.chooseBtn removeTarget:self action:@selector(chooseModel:) forControlEvents:UIControlEventTouchUpInside];
        if (!ISBLANK(self.prodName)) {
            [self.chooseBtn setTitle:[NSString stringWithFormat:@"晒单(%@)",self.prodName] forState:UIControlStateNormal];
        }else{
            [self.chooseBtn setTitle:@"晒单" forState:UIControlStateNormal];
        }
    }
}

-(void)initView{
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
    [scrollView setDelegate:self];
    [scrollView setAlwaysBounceVertical:YES];
    self.scrollView = scrollView;
    [self.view addSubview:scrollView];
    
    // 添加标题输入框
    UITextField *titleField = [[UITextField alloc]initWithFrame:CGRectMake(10,0, JXScreenW-20, 45)];
    [titleField setPlaceholder:@"标题，诱人的话会有更多人看到哦~"];
    [titleField setFont:[UIFont systemFontOfSize:14]];
    [titleField setValue:JXColor(153, 153, 153) forKeyPath:@"_placeholderLabel.textColor"];
    self.titleField = titleField;
    [self.scrollView addSubview:titleField];
    
    //添加第1条分割线
    UIView *splite1 = [[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(titleField.frame), JXScreenW-10, 0.5)];
    [splite1 setBackgroundColor:JXColor(204, 204, 204)];
    self.splite1 = splite1;
    [self.scrollView addSubview:splite1];
    
    // 添加内容输入框
    JXTextView *contentView = [[JXTextView alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(splite1.frame)+5, JXScreenW-10, 210)];
    [contentView setPlaceholder:@"内容，好内容才能上头条赢情趣大奖哦"];
    self.contentView = contentView;
    [self.scrollView addSubview:contentView];
    
    // 添加图片选择view
    PicListView *picListView = [[PicListView alloc]init];
    [picListView setY:CGRectGetMaxY(contentView.frame)+5];
    picListView.delegate = self;
    self.picListView = picListView;
    [self.scrollView addSubview:picListView];
    
    // 添加第2条输入框
    UIView *splite2 = [[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(picListView.frame)+5, JXScreenW-10, 0.5)];
    [splite2 setBackgroundColor:JXColor(204, 204, 204)];
    [self setSplite2:splite2];
    [self.scrollView addSubview:splite2];
    
    // 添加选择版块的btn
    UIButton *chooseBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(splite2.frame), JXScreenW, 45)];
    [chooseBtn setTitle:@"选择版块" forState:UIControlStateNormal];
    [chooseBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [chooseBtn setTitleColor:JXColor(51, 51, 51) forState:UIControlStateNormal];
    [chooseBtn setBackgroundImage:[UIImage imageWithColor:JXColor(204, 204, 204)] forState:UIControlStateHighlighted];
    [chooseBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [chooseBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [chooseBtn setImage:[UIImage imageNamed:@"ic_choose_bbs"] forState:UIControlStateNormal];
    [chooseBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
    [chooseBtn addTarget:self action:@selector(chooseModel:) forControlEvents:UIControlEventTouchUpInside];
    self.chooseBtn = chooseBtn;
    [self.scrollView addSubview:chooseBtn];
    
    //添加小箭头
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"self_item_arrow"]];
    [image setX:chooseBtn.width-image.width-10];
    [image setY:(chooseBtn.height-image.height)/2];
    [chooseBtn addSubview:image];
    
    UIView *splite3 = [[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(chooseBtn.frame), JXScreenW-10, 0.5)];
    [splite3 setBackgroundColor:JXColor(204, 204, 204)];
    [self setSplite3:splite3];
    [self.scrollView addSubview:splite3];
    
    UIButton *publishBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(splite3.frame)+30, JXScreenW-20, 45)];
    [publishBtn setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
    [publishBtn setTitle:@"发表" forState:UIControlStateNormal];
    [publishBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [publishBtn addTarget:self action:@selector(sendPosts) forControlEvents:UIControlEventTouchUpInside];
    self.publishBtn = publishBtn;
    [self.scrollView addSubview:publishBtn];
    
    [self.scrollView setContentSize:CGSizeMake(JXScreenW, CGRectGetMaxY(publishBtn.frame)+30)];
    
    [self addKVO];
}

-(void)chooseModel:(UIButton *)btn{
    ModelArrayView *view =[[ModelArrayView alloc]initWithModelArray:self.modelArray selectIndex:_currentModelIndex];
    view.delegate = self;
    [view show];
}

-(void)modelBtnClickWithIndex:(NSInteger)index{
    _currentModelIndex = index;
    BBSModel *model = self.modelArray[_currentModelIndex];
    [self.chooseBtn setTitle:model.name forState:UIControlStateNormal];
    
    if ([[NSString stringWithFormat:@"%@",model.modelId] isEqualToString:KEY_SUNSINGLE_ID]) {
        //是晒单
        [self getShareOrderData];
    }
}

#pragma mark - 发送帖子相关逻辑处理

-(void)sendPosts{
    if ([self isValidPost]) {
        MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view title:@"骚等"];
        self.HUD = HUD;
        //如果有图片，先上传图片
        if ([self.picListView getChildPicNum] > 0) {
            [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(notiPublish:)name:@"publish" object:nil];
            [self uploadFile];
        } else {
            [self publish:@""];
        }
    }
}

-(void)notiPublish:(NSNotification *)notification{
    NSString *imageUrls = notification.object;
    [self publish:imageUrls];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"publish" object:nil];
}

-(void)publish:(NSString *)imageUrls{
    [ForumDataTool publishNewTopicWithTitle:_titleField.text content:_contentView.text modelId:[self getCurrentModelId] imageUrls:imageUrls prodId:self.prodId success:^(JXBaseResponse *result) {
        [self.HUD hide:YES];
        if ([Utils isBlankString:result.data]) {
            [DialogUtils showTipsWithView:self.navigationController.view String:@"发帖成功\n审核后才可显示哦~"];
            [self.navigationController popViewControllerAnimated:NO];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [self.HUD hide:YES];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"发帖失败"];
    }];
}

-(NSString *)getCurrentModelId{
    if (_currentModelIndex == 0) {
        return KEY_SUNSINGLE_ID;
    }
    if (_currentModelIndex == -1) {
        return nil;
    }
    BBSModel *model = self.modelArray[_currentModelIndex];
    return model.modelId;
}

/**
 * 帖子内容是否满足条件
 *
 * @return true or false
 */
-(BOOL) isValidPost{
    if ([Utils isBlankString:[_titleField.text trim]]) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"标题不能为空"];
        return NO;
    } else if ([Utils getLengthWithStr:[_titleField.text trim]]<MIN_INPUT_WORD_FOR_TITLE) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"标题不能少于4个汉字哦~"];
        return NO;
    }
    NSString *str = [_contentView.text trim];
    if ([Utils isBlankString:str]) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"帖子内容不能为空"];
        return NO;
    } else if ([Utils getLengthWithStr:[_contentView.text trim]] < MIN_INPUT_WORD_FOR_TITLE) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"帖子内容不能少\n于4个汉字哦~"];
        return NO;
        
    }
    
    if (_currentModelIndex==-1) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"请选择板块"];
        return NO;
    }
    
    if (self.modelArray.count==0) {
        //代表self.modelArray为空，代表是纯晒单页面
        if ([self.picListView getChildPicNum] == 0) {
            [DialogUtils showTipsWithView:self.navigationController.view String:@"请选择图片"];
            return NO;
        }
    }else{
        BBSModel *model = self.modelArray[_currentModelIndex];
        if ([[NSString stringWithFormat:@"%@",model.modelId] isEqualToString:KEY_SUNSINGLE_ID] && [self.picListView getChildPicNum] == 0) {
            [DialogUtils showTipsWithView:self.navigationController.view String:@"请选择图片"];
            return NO;
        }
    }
    

    
    return YES;
}

#pragma mark - 上传图片相关操作


- (void)uploadFile{
    self.imageUrlArray = [NSMutableArray array];
    self.uy = [[UpYun alloc] init];
    __weak JXNewTopicCtl *ctl = self;
    __weak UpYun *uuy = self.uy;
    __weak UIView *showView = self.navigationController.view;
    __weak NSMutableArray *array = self.imageUrlArray;
    __weak PicListView *picVew = self.picListView;
    self.uy.successBlocker = ^(id data)
    {
        NSDictionary *dic = data;
        NSString *url = [dic objectForKey:@"url"];
        [array addObject:url];
        
        if (array.count==[picVew getChildPicNum]) {
            JXLog(@"END:%.0f",[[NSDate date] timeIntervalSince1970]);
            //最后一条已经加进来了。代表上传完成
            NSString *string = [NSString stringWithFormat:@"%@",array];
            string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            [ctl publish:string];
        }
    };
    self.uy.failBlocker = ^(NSError * error)
    {
        [uuy cancelUpLoad];
        NSString *message = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
        [array removeAllObjects];
        [ctl.HUD hide:YES];
        [DialogUtils showTipsWithView:showView String:[NSString stringWithFormat:@"上传图片失败\n%@",message]];
    };
    JXLog(@"START:%.0f",[[NSDate date] timeIntervalSince1970]);
    NSArray *imageArray = [self.picListView getImageArray];
    for (UIImage *image in imageArray) {
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [self.uy uploadFile:data saveKey:[Utils getUPYSaveKey]];
    }
}

#pragma mark 选择图片相关操作

/**
 *  添加webview的内容高度改变监听
 */
-(void)addKVO{
    [self.picListView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:@"frame"])
    {
        NSValue *oldSize = [change objectForKey:@"old"];
        NSValue *newSize = [change objectForKey:@"new"];
        if ([oldSize CGRectValue].size.height!=[newSize CGRectValue].size.height) {
            [self resetViewY];
        }
    }
}
-(void)picListViewAddPicClick:(UIButton *)btn{
    [self.view endEditing:YES];
    
    JTSActionSheetTheme *theme = [JTSActionSheetTheme defaultTheme];
    theme.separatorColor = JXColor(204, 204, 204);
    theme.normalButtonColor = JXThemeColor;
    theme.destructiveButtonColor = [UIColor blackColor];
    theme.titleColor = JXThemeColor;
    theme.cancelButtonColor = [UIColor blackColor];
    
    JTSActionSheetItem *buyAll = [JTSActionSheetItem itemWithTitle:@"拍照" action:^{
        //前往拍照
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.delegate = self;
        //        _imagePickerController.allowsEditing = YES;
        //设置拍照时的下方的工具栏是否显示，如果需要自定义拍摄界面，则可把该工具栏隐藏
        _imagePickerController.showsCameraControls  = YES;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    } isDestructive:NO];
    
    JTSActionSheetItem *deleteAll = [JTSActionSheetItem itemWithTitle:@"从手机相册选择" action:^{
        //前往手机相册
        ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
        picker.maximumNumberOfSelection = [self.picListView getCanAddPicNum];
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups=NO;
        picker.delegate=self;
        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 5;
            } else {
                return YES;
            }
        }];
        
        [self presentViewController:picker animated:YES completion:nil];
    } isDestructive:NO];
    
    JTSActionSheetItem *cancel = [JTSActionSheetItem itemWithTitle:@"取消" action:^{
    } isDestructive:NO];
    
    JTSActionSheet *sheet = [[JTSActionSheet alloc] initWithTheme:theme
                                                            title:nil
                                                      actionItems:@[buyAll, deleteAll]
                                                       cancelItem:cancel];
    [sheet showInView:self.view];
    
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取图片裁剪的图
    UIImage* tempImg = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [self.picListView addImage:tempImg];
    //模态方式退出uiimagepickercontroller
    [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    __block float fileKB  = 0.0;
    double perMBBytes = 1024.0;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 处理耗时操作的代码块...
        for (int i=0; i<assets.count; i++) {
            ALAsset *asset=assets[i];
            //计算image的大小(kb)
            ALAssetRepresentation *representation = [asset defaultRepresentation];
            fileKB = (double)([representation size]/perMBBytes);
            JXLog(@"size of asset in bytes: %0.2f kb", fileKB);
            UIImage *tempImg = nil;
            if (fileKB>300) {
                //需要压缩
                //                NSData *data = UIImageJPEGRepresentation([UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage], 0.75);
                //                tempImg = [UIImage imageWithData:data];
                tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            }else{
                tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新
                [self.picListView addImage:tempImg];
            });
        }
    });
}

-(void)resetViewY{
    [self.splite1 setY:CGRectGetMaxY(self.titleField.frame)];
    [self.contentView setY:CGRectGetMaxY(self.splite1.frame)+5];
    [self.picListView setY:CGRectGetMaxY(self.contentView.frame)+5];
    [self.splite2 setY:CGRectGetMaxY(self.picListView.frame)+5];
    [self.chooseBtn setY:CGRectGetMaxY(self.splite2.frame)];
    [self.splite3 setY:CGRectGetMaxY(self.chooseBtn.frame)];
    [self.publishBtn setY:CGRectGetMaxY(self.splite3.frame)+30];
    [self.scrollView setContentSize:CGSizeMake(JXScreenW, CGRectGetMaxY(self.publishBtn.frame)+30)];
    
}


//晒单
//以下是晒单需要的方法

-(void)getShareOrderData{
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:@"1" forKey:@"pageIndex"];
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    [loding show:YES];
    [SelfDataTool getShareOrderList:params success:^(ShareProductRes *result) {
        [loding hide:YES];
        ShareOrderPopView *shareOrderView =  [[ShareOrderPopView alloc]init];
        shareOrderView.width = JXScreenW-60;
        [shareOrderView setDelegate:self];
        //设置数据
        [shareOrderView setShareProductData:result];
        //显示在弹出窗体中
        CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:shareOrderView];
        [showView showWithanim:NO];
    } failure:^(NSError *error) {
        [loding hide:YES];
        [DialogUtils showTipsWithView:self.view String:@"加载晒单数据失败"];
    }];
}

-(void)shareOrder:(CartProdSub *)prod{
    if (prod) {
        self.prodId = prod.prodId;
        [self.chooseBtn setTitle:[NSString stringWithFormat:@"晒单(%@)",prod.prodName] forState:UIControlStateNormal];
    }
}



- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

-(void)dealloc{
    [self.picListView removeObserver:self forKeyPath:@"frame"];
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(notiPublish:)name:@"publish" object:nil];
}

-(BOOL)shouldLogin{
    return YES;
}



@end
